/**
 * Created by Feng on 2016/3/25.
 */
import {provide, Directive, forwardRef,Input} from '@angular/core';
import {Control,NG_VALIDATORS,Validator} from '@angular/common';
import {Observable} from 'rxjs/Observable';
/* beautify ignore:end */

@Directive({
    selector: '[unique]',
    providers: [provide(NG_VALIDATORS, {useExisting: UniqueValidator, multi: true})]
})

export class UniqueValidator implements Validator {
    private _dataList: Array<any>;
    private _name: string;
    
    @Input()
    set dataList(dataList: any) {
        this._dataList = dataList;
    }
    
    get dataList() {
        return this._dataList;
    }

     @Input()
    set uniqueName(name: any) {
        this._name = name;
    }
    
    get uniqueName() {
        return this._name;
    }
    
    constructor(
    ) {}
 
    validate(c: Control): {[key: string]: any} {  
        if(c.value) { 
          for(let d of this._dataList) {
            if( c.value == d[this._name]) { 
                return {'unique': true};
            }
          }
        }
    }
}